package com.ruoyi.common.mq.rabbit.service;

import com.rabbitmq.client.Channel;
import com.ruoyi.common.mq.rabbit.config.RabbitMQConfig;
import com.ruoyi.system.api.domain.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class Receiver {

    @Autowired
    private LogService logService;

    @RabbitListener(queues = RabbitMQConfig.LOG_QUEUE)
    public void handleLog(@Payload SysOperLog message,
                          @Headers Map<String, Object> headers,
                          Channel channel) throws IOException {
        log.info("Received log message: {}", message);
        try {
            // 处理operParam转换
            if (message.getOperParam() != null && !(message.getOperParam() instanceof String)) {
                message.setOperParam(message.getOperParam().toString());
            }

            logService.saveSysLog(message);
            channel.basicAck((Long)headers.get(AmqpHeaders.DELIVERY_TAG), false);
        } catch (Exception e) {
            log.error("Failed to process log message: {}", message, e);
            channel.basicNack((Long)headers.get(AmqpHeaders.DELIVERY_TAG), false, false);
        }
    }
}